import { login, smsLogin } from '@/api/user/userApi'
import { LoginParm } from '@/api/user/userModel'
import { Result } from '@/http/request'
import { ActionContext } from 'vuex'
import { RootState } from '..'

export type UserState = {
  token: string
  userId: string
  userName: string
  deptName: string
  deptId: string
  roleName: string
  collapse: boolean
}

export const state: UserState = {
  token: '',
  userId: '',
  deptName: '',
  deptId: '',
  roleName: '',
  userName: '',
  collapse: false
}

export const mutations = {
  setData: (state: UserState, data: any) => {
    state.token = data.token
    state.userId = data.userId
    state.userName = data.userName
    state.deptName = data.deptName
    state.deptId = data.deptId
    state.roleName = data.roleName
  },
  //设置collapse
  setCollapse: (state: UserState, collapse: boolean) => {
    state.collapse = collapse
  }
}

export const actions = {
  login({ commit }: ActionContext<UserState, RootState>, loginParm: LoginParm) {
    return new Promise<Result>((resolve, reject) => {
      smsLogin(loginParm)
        .then(res => {
          login(res)
            .then(loginRes => {
              let data = loginRes.data
              commit('setData', data)
              resolve(res)
            })
            .catch(error => {
              reject(error)
            })
        })
        .catch(error => {
          reject(error)
        })
    })
  }
}

export const getters = {
  getUserInfo: (state: UserState): UserState => {
    return state
  },
  //获取collapse
  getCollapse: (state: UserState): boolean => {
    return state.collapse
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
